<?php
// last modified: 19/08/2009
// This file is part of Moodle - http://moodle.org/  
// 
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * This is the local hack file as part of MDL-19430:
 * "user-determined order and number of courses on myMoodle"
 * http://tracker.moodle.org/browse/MDL-19430
 * 
 * This requires MDL-17446 to work.
 * In this file, a replacement for myMoodle is created, to make it sortable
 * also allows users to hide a number of courses
 * 1: users have the option to change the order of courses on myMoodle
 *    by clicking up and down arrows while in editing mode.
 * 2: user can choose how many courses are displayed on myMoodle by changing
 *    the number in the drop-down box while in editing mode.
 * 3: course details such as due assignments are initially collapsed when
 *    the myMoodle page is loaded. they can be unfolded by clicking an icon.
 *
 * @package local
 * @copyright 2009 Minh-Tam R. Nguyen (minhtam@minhtam.info)
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
require_once('../config.php');
//style_sheet_setup(time(), $lifetime, $themename, $forceconfig, $lang);
//echo '<link rel="stylesheet" type="text/css" href="'.$CFG->wwwroot.'/local/styles.php">';

/**
 * This function gets called instead of {@link print_overview($courses)}.
 * It retrieves the courses a user has access to, sorts them and prints
 * the desired number of them in the centre column.
 * In editing mode, all courses are displayed and the user can choose
 * the order and how many should be displayed normally.
 */
function local_my_moodle() {
    global $CFG, $USER, $PAGE;

    // do not limit the number of courses showing up: retrieve them all
	// Oct. 2009: there needs to be a limit, as retrieving 50 courses takes a while. 
	// TODO: add permissions
	// TODO: add pagination
    $courses = get_my_courses($USER->id, 'visible DESC,sortorder ASC', '*', false, 5);
    $site = get_site();
	
    // before printing the courses, show the user's picture, name and
    // messages (like profie)
    print_welcome_block();
    
    // now print the courses in the centre column
    print_box_start('coursebox notice');
    $displayOnly = 0;
    $displayOnly = $USER->mynumber; // number of courses to display. Stored in user profile field "mynumber"
    if ($PAGE->user_is_editing()) {
	// when in editing mode display a dropdown list to let the user select how many courses should be displayed
        echo '<form name="myNumCourses" action="'.$CFG->wwwroot.'/local/num.php" method="post" id="myNumCourses">';    
        echo '<label for="myNumCourses">'.get_string('display_only_e','local',$displayOnly).'</label>';
        echo '<select name="myNumCourses" onchange="submitForm()">';
        echo '<option value="0">'.get_string('dropdown_all', 'local').'</option>';
        for ($o = 1; $o <= count($courses); $o++) {
            echo '<option ';
            if ($o == $displayOnly) {
                echo 'selected="'.$o.'" '; 
            }
            echo 'value="'.$o.'">'.get_string('dropdown_n', 'local',$o).'</option>';
        }
        echo '</select>';
//        echo '<input id="id" type="hidden" value="'.$USER->id.'"/>';
        echo '<input id="submitBtn" type="submit" value="'.get_string('button_save', 'local').'" class="btn"/>';
		// remind user to turn editing off again:
		echo ' &nbsp; <a href="index.php?edit=off&amp;sesskey='.sesskey().'">'.get_string('more_courses_e1','local').'</a>';
	    if (($displayOnly < count($courses)) && ($displayOnly != 0)) {
            echo get_string('more_courses_e2','local',count($courses)-$displayOnly);
		}
        echo '</form>';
		// JavaScript users don't see submit button. They get to submit when selecting from list.
        echo '<script language="JavaScript">
        <!--
        var btn = document.getElementById("submitBtn");
        btn.style.display = "none";
        function submitForm()
        {
            document.myNumCourses.submit();
        }
        // -->
        </script> ';
    } else {
	// when in normal mode, display some descriptive text instead of the form
        if (($displayOnly > 0) && ($displayOnly < count($courses))) {
            echo get_string('display_only1','local',$displayOnly);
            echo get_string('display_only2','local',count($courses));
            echo '<a href="index.php?edit=on&amp;sesskey='.sesskey().'">'.get_string('display_only3','local').'</a>';
            echo get_string('display_only4','local');
        } else {
		// 'all' courses
            echo get_string('display_all','local');
            echo '<a href="index.php?edit=on&amp;sesskey='.sesskey().'">'.get_string('display_only3','local').'</a>';
            echo get_string('display_only4','local');
        }
    }
    print_box_end();
    
	// start printing the courses    
    if (array_key_exists($site->id,$courses)) {
        unset($courses[$site->id]);
    }

    foreach ($courses as $c) {
        if (isset($USER->lastcourseaccess[$c->id])) {
            $courses[$c->id]->lastaccess = $USER->lastcourseaccess[$c->id];
        } else {
            $courses[$c->id]->lastaccess = 0;
        }
    }
    if (empty($courses)) {
        print_simple_box(get_string('nocourses','my'),'center');
    } else {
        local_print_overview($courses, $displayOnly);
    }
	// now have finished printing the courses

    // if the user has access to more courses than he/she wants to see, 
	// display a notice to make sure they aren't missed
    print_box_start('coursebox notice');
    if ($PAGE->user_is_editing()) {
//        echo '<img src="'.$CFG->pixpath.'/i/edit.gif" class="icon" alt="" />';
        echo '<a href="index.php?edit=off&amp;sesskey='.sesskey().'">'.get_string('more_courses_e1','local').'</a>';
	    if (($displayOnly < count($courses)) && ($displayOnly != 0)) {
            echo get_string('more_courses_e2','local',count($courses)-$displayOnly);
		}
    } else {
        if (($displayOnly > 0) && ($displayOnly < count($courses))) {
            echo get_string('more_courses1','local',count($courses)-$displayOnly);
            echo '<a href="index.php?edit=on&amp;sesskey='.sesskey().'">'.get_string('more_courses2','local').'</a>';
            echo get_string('more_courses3','local');
        } else {
		// 'all' courses
            echo get_string('display_all','local');
            echo '<a href="index.php?edit=on&amp;sesskey='.sesskey().'">'.get_string('display_only3','local').'</a>';
            echo get_string('display_only4','local');
        }
    }

    print_box_end();
}

/**
 * This function prints the user's profile picture, a welcome message and
 * the number of messages, a little bit like the profile.
 */
function print_welcome_block() {
    global $CFG, $USER, $PAGE;
    $site = get_site();
    // before printing the courses, show the user's picture, name and
    // messages (like profie)
    print_box_start('top');
    print_box_start('picture');
    print_user_picture($USER, $site->id, $USER->picture, true, false, false);
    print_box_end();
    print_box_start('welcome');    
    echo '<h2>'.get_string('welcome','local',$USER->firstname).'</h2>';
	// it would be useful to have a link to edit the profile when editing the page
	if ($PAGE->user_is_editing()) {
	    echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$USER->id.'">';
        echo get_string('view_edit_profile','local').'</a><br />';
    }
    if (!empty($CFG->messaging) and !isguest() and has_capability('moodle/site:sendmessage', get_context_instance(CONTEXT_SYSTEM))) {
        if (!empty($USER->id)) {
            if ($countmessages = count_records('message', 'useridto', $USER->id)) {
                echo get_string('you_have_messages','local',$countmessages);
            } else {
                echo get_string('you_have_no_messages','local');
            }
            echo '<a href="'.$CFG->wwwroot.'/message/index.php" onclick="openpopup(\'/message/index.php\', \'message\', \'menubar=0,location=0,scrollbars,status,resizable,width=400,height=500\', 0);return false;">';
            if ($countmessages == 1) {
                echo get_string('message','local');
            } else {
                echo get_string('messages','local');
            }
            echo '</a>';
        }
    }    
    print_box_end();
    print_box_start('flush');
    print_box_end();
    print_box_end();
}

/**
 * This function saves the user's desired order of courses
 * in the centre column of myMoodle.
 * This function uses some of the profile methods for custom user profile fields. 
 *
 * @param int $uid The user's ID for whom the order should be set
 * @param array $order This is an array containing the order of course IDs
 * @return string $orderstr This is a comma-concatenated string of course IDs
 */
function set_myorder($uid,$order) {
    global $USER;
    require_once('../user/profile/lib.php');
    if (($orderstr = implode(',',$order)) && ($fields = get_records_select('user_info_field'," shortname = 'myorder' "))) {
        foreach ($fields as $field) {
			$data = new object();
			$data->userid  = $uid;
			$data->fieldid = $field->id;
			$data->data    = $orderstr;
			if ($dataid = get_field('user_info_data', 'id', 'userid', $data->userid, 'fieldid', $data->fieldid)) {
				// row already exists
				$data->id = $dataid;
				if (!update_record('user_info_data', $data)) {
					error(get_string('update_order_fail', 'local'));
				}
			} else {
			// new row
			insert_record('user_info_data', $data);
			}
			$USER->myorder = $orderstr;
			return $orderstr;       
        }
    } else {
        error(get_string('need_field', 'local'));
    }
}

/**
 * This function saves the user's desired number of courses
 * to be displayed in the centre column of myMoodle.
 * This function uses some of the profile methods for custom user profile fields. 
 *
 * @param int $uid The user's ID for whom the order should be set
 * @param int $myNumCourses This is number of courses to be shown on myMoodle
 * @return int $myNumCourses This is number of courses to be shown on myMoodle
 */
function set_mynumber($uid,$myNumCourses) {
    global $USER;
    require_once('../user/profile/lib.php');
    if ($fields = get_records_select('user_info_field'," shortname = 'mynumber' ")) {
        foreach ($fields as $field) {
			$data = new object();
			$data->userid  = $uid;
			$data->fieldid = $field->id;
			$data->data    = $myNumCourses;
			if ($dataid = get_field('user_info_data', 'id', 'userid', $data->userid, 'fieldid', $data->fieldid)) {
				// row already exists
				$data->id = $dataid;
				if (!update_record('user_info_data', $data)) {
					error(get_string('update_order_fail', 'local'));
				}
			} else {
			// new row
			insert_record('user_info_data', $data);
			}
			$USER->mynumber = $myNumCourses;
			return $myNumCourses;       
        }
    } else {
        error(get_string('need_field', 'local'));
    }
}

/**
 * This function sorts an array by another. Any elements that couldn't
 * be sorted are stuck to the front.
 * This will sort the courses a user has access to as determined by the
 * preferred order saved in the profile. New courses (since the last sorting)
 * get stuck to the front so that they get listed first.
 *
 * @param array $array The array to be sorted
 * @param array $orderArray The array with elements in the desired order
 * @return array An array in the desired order, with unmentioned elements at the start
 */
function sortArrayByArray($array,$orderArray) {
    $ordered = array();
    foreach($orderArray as $key) {
        if(array_key_exists($key,$array)) {
                $ordered[$key] = $array[$key];
                unset($array[$key]);
        }
    }
    return $array + $ordered;
}

/**
 * This function performs the functions normally performed by {@link print_overview()}
 * It lists the courses the user has access to. In addition to the usual listing, 
 * the courses are sorted according to preference, and the number of courses to be
 * displayed is respected.
 *
 * @param array $courses The array to be sorted
 * @param int $displayOrder The number of courses to be displayed
 */
function local_print_overview($courses, $displayOnly=0){
    global $CFG, $USER, $PAGE;

    $htmlarray = array();
    // collapsed course details - only when not editing
    if (!($PAGE->user_is_editing())) {// don't show details when editing
    echo '<script language="javascript" type="text/javascript">
    <!--
    function addEvent(obj, evType, fn){ 
        if (obj.addEventListener){ 
            obj.addEventListener(evType, fn, false); 
            return true; 
        } else if (obj.attachEvent){ 
            var r = obj.attachEvent("on"+evType, fn); 
            return r; 
        } else { 
            return false; 
        } 
    }
    // -->
    </script>';
    echo '<script language="javascript" type="text/javascript">
    <!--
    function toggle_details(id) {
        var details = document.getElementById("details"+id);
            if (details.style.display != "none") {
            details.style.display = "none";
            document.getElementById("plusminus"+id).setAttribute("src", "'.$CFG->wwwroot.'/local/images/MyPlus.jpg");
            document.getElementById("plusminus"+id).setAttribute("alt", "'.get_string('show_details', 'local').'");
        } else {
            details.style.display = "";
            document.getElementById("plusminus"+id).setAttribute("src", "'.$CFG->wwwroot.'/local/images/MyMinus.jpg");
            document.getElementById("plusminus"+id).setAttribute("alt", "'.get_string('hide_details', 'local').'");
        }
    }
    // -->
    </script>';
    }
    
    // sort by array - this takes the comma delimited list of courses in the myorder filed and sorts courses by that. 
    $preforder = array();
    $preforder = explode(",",$USER->myorder);
    $courses = sortArrayByArray($courses,$preforder);
    if ($preforder != array_keys($courses)) {
      set_myorder($USER->id,array_keys($courses));
    }

    // remove editing part if details should be shown when editing
    if (($modules = get_records('modules')) && (!$PAGE->user_is_editing())) { 
        foreach ($modules as $mod) {
            if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
                include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
                $fname = $mod->name.'_print_overview';
                if (function_exists($fname)) {
                    $fname($courses,$htmlarray);
                }
            }
        }
    }
    
    $count = 0;
    foreach ($courses as $course) {
        $count++;
        if (($count <= $displayOnly) || ($displayOnly == 0) || ($PAGE->user_is_editing())) {
            print_simple_box_start('center', '100%', '', 5, "coursebox");
            $linkcss = '';
            if (($count > $displayOnly) && ($displayOnly != 0) && ($PAGE->user_is_editing())) {
                $linkcss = 'class="dontdisplay"';
            }
            if (empty($course->visible)) {
                $linkcss = 'class="dimmed"';
            }
			// don't show details when editing
            if (!($PAGE->user_is_editing())) {
                // course details in separate div
                print_box_start('small');
                    if (array_key_exists($course->id,$htmlarray)) {
                        echo '<a href="javascript:toggle_details('.$course->id.')">';
                        echo get_string('more_details', 'local');
                        echo '<img id="plusminus'.$course->id.'" alt="&nbsp;"></a>';
                    } else {
                        echo '&nbsp;';
                    }
				print_box_end();
            } else if ($PAGE->user_is_editing()) { // move courses
                print_box_start('small');
                if ($count!=1) {
                    echo '<a href="'.$CFG->wwwroot.'/local/move.php?id='.$course->id.'&m=t"><img src="'.$CFG->wwwroot.'/local/images/Top.gif" alt="'.get_string('move_top', 'local').'"></a>';
	    		}
                print_box_end();
                print_box_start('small');
                if ($count!=1) {
			        echo '<a href="'.$CFG->wwwroot.'/local/move.php?id='.$course->id.'&m=u"><img src="'.$CFG->wwwroot.'/local/images/Up.gif" alt="'.get_string('move_up', 'local').'"></a>';
	    		}
                print_box_end();
                print_box_start('small');
		    	if ($count!=count($courses)) {
                    echo '<a href="'.$CFG->wwwroot.'/local/move.php?id='.$course->id.'&m=d"><img src="'.$CFG->wwwroot.'/local/images/Down.gif" alt="'.get_string('move_down', 'local').'"></a>';
                }
                print_box_end();
                print_box_start('small');
		    	if ($count!=count($courses)) {
		    		echo '<a href="'.$CFG->wwwroot.'/local/move.php?id='.$course->id.'&m=b"><img src="'.$CFG->wwwroot.'/local/images/Bottom.gif" alt="'.get_string('move_bottom', 'local').'"></a>';
                }
                print_box_end();
            }
			
            print_box_start('ctitle');    
            print_heading('<a title="'. format_string($course->fullname).'" '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>');        
            print_box_end();

            if (array_key_exists($course->id,$htmlarray)) {
                print_box_start('details', 'details'.$course->id);
                // collapse course details
                echo '<script language="javascript" type="text/javascript">
                <!--
                addEvent(window,"load",toggle_details('.$course->id.'));
                // -->
                </script>';
    
                foreach ($htmlarray[$course->id] as $modname => $html) {    
                    echo $html;
                }
                print_box_end();
            }
            print_box_start('flush');
            print_box_end();
            print_simple_box_end();            
        } 
		if (($count == $displayOnly) && ($displayOnly < count($courses)) && ($PAGE->user_is_editing())) {
			print_box_start('coursebox notice');
	//        echo '<img src="'.$CFG->pixpath.'/i/edit.gif" class="icon" alt="" />';
			echo '<a href="index.php?edit=off&amp;sesskey='.sesskey().'">'.get_string('more_courses_m1','local').'</a>';
			echo get_string('more_courses_m2','local',count($courses)-$displayOnly);
			print_box_end();
		}
    }
}
